package game.editer;

import echo.math.Vector2;
import echo.Body;
import game.worlds.IAttackDisplay;
import echo.shape.Polygon;
import hx.display.Graphics;
import hx.events.Keyboard;
import hx.events.KeyboardEvent;
import hx.geom.Point;
import hx.events.MouseEvent;
import game.worlds.GameRole;
import game.worlds.World;

/**
 * 编辑器中使用的角色
 */
class EditerWorld extends World {
	/**
	 * 游戏角色
	 */
	public var role:GameRole;

	override function onInit() {
		super.onInit();
		// 初始化Echo碰撞地图数据
		this.initEchoWorld({width: 800, height: 600, gravity_y: 0});
		this.updateEnabled = true;
		this.debug = true;
	}

	override function onAddToStage() {
		super.onAddToStage();
		stage.addEventListener(MouseEvent.MOUSE_DOWN, onCollisionMouseEvent);
		stage.addEventListener(MouseEvent.MOUSE_MOVE, onCollisionMouseEvent);
		stage.addEventListener(MouseEvent.MOUSE_UP, onCollisionMouseEvent);
		stage.addEventListener(KeyboardEvent.KEY_DOWN, onKeyDown);
	}

	private function onKeyDown(e:KeyboardEvent) {
		if (e.keyCode == Keyboard.ENTER) {
			// 确定碰撞块处理
			endCollisionDarwing();
		} else if (e.keyCode == Keyboard.ESCAPE) {
			__collisions = [];
			endCollisionDarwing();
		}
	}

	override function onUpdate(dt:Float) {
		if (EditerStage.timeline.isPreview) {
			super.onUpdate(dt);
			this.onEchoUpdate(dt);
		} else {
			if (debug) {
				__echoDebug.clear();
				this.onDebugDraw();
				this.worldBox.addChild(__echoDebug.canvas);
			}
		}
	}

	override function onDebugDraw() {
		if (role != null) {
			for (object in displayBox.children) {
				if (object is IAttackDisplay) {
					var attackDisplay = cast(object, IAttackDisplay);
					if (attackDisplay.currentHitColliderFrameData != null && attackDisplay.currentHitColliderFrameData.collision != null) {
						var hitCollider = attackDisplay.currentHitColliderFrameData.collision;
						for (shape in hitCollider.shapes) {
							shape.x = object.x;
							shape.y = object.y;
							shape.scale_x = object.scaleX * role.assets.data.attrData.getBodyScale();
							shape.scale_y = object.scaleY * role.assets.data.attrData.getBodyScale();
							__echoDebug.draw_shape(shape);
						}
					}
				}
			}
		}
	}

	private var __downPos:Point = new Point();

	private var __isDown:Bool = false;

	private var __moveing:Bool = false;

	private var __collisions:Array<Point> = [];

	private var __collisionShape:Graphics = new Graphics();

	private function onCollisionMouseEvent(e:MouseEvent):Void {
		switch e.type {
			case MouseEvent.MOUSE_DOWN:
				__downPos.x = this.mouseX;
				__downPos.y = this.mouseY;
				if (e.isCtrlOrCommand) {
					__isDown = true;
					drawCollisionPoint(__downPos.clone());
				} else {
					__collisions = [];
					endCollisionDarwing();
				}
			case MouseEvent.MOUSE_MOVE:
				if (__isDown
					&& (__collisions.length == 1 || __moveing)
					&& (Math.abs(__downPos.x - this.mouseX) > 10 || Math.abs(__downPos.y - this.mouseY) > 10)) {
					__moveing = true;
					__collisions = [];
					__collisions[0] = __downPos.clone();
					__collisions[1] = new Point(this.mouseX, this.__downPos.y);
					__collisions[2] = new Point(this.mouseX, this.mouseY);
					__collisions[3] = new Point(__downPos.x, this.mouseY);
					drawCollisionPoint();
				}
			case MouseEvent.MOUSE_UP:
				if (__isDown) {
					__isDown = false;
					if (__moveing && e.isCtrlOrCommand) {
						// 产生4边型，立即产生
						endCollisionDarwing();
					}
				}
		}
	}

	public function drawCollisionPoint(point:Point = null):Void {
		if (point != null)
			__collisions.push(point);
		// 开始绘制碰撞块
		if (__collisions.length == 1) {
			this.worldBox.addChild(__collisionShape);
		}
		__collisionShape.clear();
		__collisionShape.beginLineStyle(0xffff00, 2);
		if (__collisions.length < 1)
			return;
		for (i => point in __collisions) {
			if (i == 0)
				__collisionShape.moveTo(point.x, point.y);
			else
				__collisionShape.lineTo(point.x, point.y);
		}
		// 绘制点位
		var size = 6;
		for (point in __collisions) {
			__collisionShape.beginFill(0xffff00);
			__collisionShape.drawRect(point.x - size * 0.5, point.y - size * 0.5, size, size);
		}
		if (__moveing) {
			__collisionShape.lineTo(__collisions[0].x, __collisions[0].y);
		}
	}

	public function endCollisionDarwing():Void {
		__collisionShape.remove();
		if (__collisions.length < 3) {
			return;
		}
		if (EditerStage.timeline.currentFrameData != null) {
			var vectors = [];
			var x = EditerStage.timeline.getCurrentTimeLineEffect() != null ? EditerStage.timeline.getCurrentTimeLineEffect().x : this.role.x;
			var y = EditerStage.timeline.getCurrentTimeLineEffect() != null ? EditerStage.timeline.getCurrentTimeLineEffect().y : this.role.y;
			var scaleX = EditerStage.timeline.getCurrentTimeLineEffect() != null ? EditerStage.timeline.getCurrentTimeLineEffect().scaleX : this.role.scaleX;
			var scaleY = EditerStage.timeline.getCurrentTimeLineEffect() != null ? EditerStage.timeline.getCurrentTimeLineEffect().scaleY : this.role.scaleY;
			for (point in __collisions) {
				vectors.push(new Vector2((point.x - x) / scaleX, (point.y - y) / scaleY));
			}
			if (EditerStage.timeline.currentFrameData.collision == null) {
				EditerStage.timeline.currentFrameData.collision = new Body();
			}
			var p = Polygon.get();
			p.set_vertices(vectors);
			EditerStage.timeline.currentFrameData.collision.add_shape(p);
			if (EditerStage.timeline.currentFrameData.collisionLiveTime <= 0) {
				EditerStage.timeline.currentFrameData.collisionLiveTime = 3 / EditerStage.timeline.currentActionData.fps;
			}
			// 更新时间轴
			EditerStage.timeline.updateTimelineData(true);
		}
		__collisions = [];
	}
}
